<template>
    <el-dialog @close="cancleAddDict" v-model="dialogVisible" width="30%" title="新增检测项信息" destroy-on-close center>
        <template #default>
            <el-form :model="dict" label-position="right" label-width="100px">

              <el-form-item label="*检测项编码">
                <el-input v-if="!autoGenerate" v-model="dict.checkItemId"></el-input>
                <el-switch v-model="autoGenerate" active-text="启用自动编码" inactive-text="禁用"
                           @change="handleSwitchChange"/>
              </el-form-item>

                <el-form-item label="*检测项名称">
                    <el-input v-model="dict.checkItemName" placeholder="请输入检测项名称" />
                </el-form-item>
              <el-form-item label="检测项类型">
                <el-select
                    style="width: 100px"
                    v-model="dict.checkItemType"
                    placeholder="选择类型"
                >

                  <el-option v-for="item in types" :key="item.checkItemType" :value="item.checkItemType" :label="item.checkItemType"/>
                </el-select>
              </el-form-item>
                <el-form-item label="检测工具">
                    <el-input  v-model="dict.checkItemTools" placeholder="请输入检测工具" />
                </el-form-item>
              <el-form-item label="备注">
                <el-input type="textarea" v-model="dict.note" placeholder="请输入内容" />
              </el-form-item>

            </el-form>
        </template>
        <!-- footer插槽中放两个按钮 -->
        <template #footer>
            <el-row>
                <el-col :span="12">
                    <el-button type="primary" @click="addDict">确定</el-button>
                </el-col>
                <el-col :span="12">
                    <el-button type="primary" @click="cancleAddDict">取消</el-button>
                </el-col>
            </el-row>
        </template>
    </el-dialog>
</template>
<script>
import { watch } from "vue";
// 引入我们申明的dict的api的js
import FlawItemRequest from "@/api/flawItem.js";
import axios from 'axios';
export default {
    props: ["visible"],
    emits: ["optionCompleted"], // 对外暴露一个事件，用来传递添加学生的操作结果
    data() {
        return {
            dict: {},// 绑定新增的字典信息
            dialogVisible: false,// 添加字典窗口的显示与隐藏
            types:{},
          autoGenerate:false,

          CHECK_No:'CHECK_NO',
        }
    },
     methods: {
       /**
        * 编号的自动生成
        */
       getAutoNumber(rulesName, callBack) {
         // let url = this.BASE_URL + "/rules/query";
         let url = "http://localhost:8086/qc/rules/query?rulesName=CHECK_NO";

         // 假设使用Axios发送GET请求
         axios.get(url)
             .then(response => {
               console.log(response.data);
               // 获取到自动生成的编码后执行回调函数
               callBack(response.data);
             })
             .catch(error => {
               // 错误处理
               console.error('Error fetching auto number:', error);
             });
       },
       handleSwitchChange(value) {
         this.autoGenerate = value;
         if (value) {
           // 开启自动生成编码时调用获取编码的方法
           this.getAutoNumber("TEMPLATE_NO", autoNumber => {
             this.dict.checkItemId = autoNumber.data;
           });
         }
       },

        /**
         * 取消添加学生的事件
         */
        cancleAddDict(){
            this.dict = {};
            // 通知父组件  操作完成，让父组件关闭窗体
            this.$emit("optionCompleted");
        },
        /**
         * 添加学生信息
         */
        addDict(){
            FlawItemRequest.addFlawItem(this.dict,res=>{
                if (res.code == '200'){
                    this.$message({
                        type: 'success',
                        message: '添加成功!'
                    });
                    // 通知父组件  操作完成，让父组件关闭窗体
                    this.$emit("optionCompleted");
                }else if(res.code == '300'){
                    this.$message({
                        type: 'warning',
                        message: '字典' + (res.msg.indexOf("checkItemName") > 0 ?"名称":"类型") + "重复"
                    });
                }else{
                    this.$message({
                        type: 'error',
                        message: '添加字典失败!'
                    });
                }
            });
        },

       /**
        * 加载所有信息
        */
       loadDictAll(){
         FlawItemRequest.loadFlawItemAll(res => {
           const types = res.data.map(item => {
             return {
               checkItemType: item.checkItemType,
             }
           })
           let seen = {};
           let filteredArr = types.filter(item => {
             let key = item.checkItemType ;
             if (!seen[key]) {
               seen[key] = true;
               return true;
             }
             return false;
           });
           this.types = filteredArr;
           console.log(this.types);
         })
       },

  }, mounted(props) {
      this.loadDictAll();
        // 侦听props   一旦发生变化，就会出发下面的函数
        watch(() => this.visible, (newVal, oldVal) => {
            // 将最新的值设置给弹窗的dialogVisible属性
            this.dialogVisible = newVal;
        });
    }
}
</script>